// members.js
const app = getApp()

Page({
  data: {
    members: [],
    totalMembers: 0,
    activeMembers: 0,
    newMembers: 0,
    showModal: false,
    editingMember: null,
    memberForm: {
      nickname: '',
      role: 'member',
      phone: '',
      status: 'active',
      avatar: '',
      points: 0
    },
    roles: ['家庭成员', '厨师'],
    roleIndex: 0,
    // 积分管理相关
    showPointsModal: false,
    selectedMember: null,
    pointsAdjustment: '',
    pointsSetValue: ''
  },

  onLoad() {
    console.log('=== 成员管理页面加载 ===')
    console.log('全局家庭信息:', app.globalData.familyInfo)
    console.log('全局用户信息:', app.globalData.userInfo)
    console.log('全局登录状态:', app.globalData.isLoggedIn)
    console.log('=== 成员管理页面加载结束 ===')
    
    this.loadMembers()
  },

  onShow() {
    this.loadMembers()
  },

  // 加载成员数据
  async loadMembers() {
    try {
      // 检查家庭信息
      if (!app.globalData.familyInfo) {
        console.error('无法加载成员：全局家庭信息缺失')
        this.showFamilyInfoError()
        return
      }
      
      // 使用固定家庭ID
      const familyId = 'xiaoweichufang'
      console.log('开始加载家庭成员，familyId:', familyId)
      
      // 从云数据库加载成员数据
      const { userService } = require('../../../utils/cloud.js')
      
      const result = await userService.getFamilyMembers(familyId)
      
      if (result.success) {
        const members = result.data || []
        
        // 计算统计数据
        const totalMembers = members.length
        const activeMembers = members.filter(member => member.status === 'active').length
        const currentMonth = new Date().getMonth()
        const newMembers = members.filter(member => {
          const joinMonth = new Date(member.joinTime).getMonth()
          return joinMonth === currentMonth
        }).length

        this.setData({
          members,
          totalMembers,
          activeMembers,
          newMembers
        })
        
        // 更新全局数据
        app.globalData.familyInfo.members = members
        
        console.log(`从云数据库加载成员成功，共 ${members.length} 个成员`)
      } else {
        console.error('从云数据库加载成员失败:', result.error)
        // 如果云数据库加载失败，使用本地数据
        this.loadLocalMembers()
      }
    } catch (error) {
      console.error('加载成员数据失败:', error)
      // 出错时使用本地数据
      this.loadLocalMembers()
    }
  },

  // 显示家庭信息错误提示
  showFamilyInfoError() {
    this.setData({
      members: [],
      totalMembers: 0,
      activeMembers: 0,
      newMembers: 0
    })
    
    wx.showModal({
      title: '家庭信息缺失',
      content: '无法加载成员信息，请重新登录或联系管理员',
      showCancel: false,
      confirmText: '知道了',
      success: () => {
        // 可以跳转到登录页面
        wx.navigateTo({
          url: '/pages/auth/login/login'
        })
      }
    })
  },

  // 加载本地成员数据（备用方案）
  loadLocalMembers() {
    const familyInfo = app.globalData.familyInfo || {}
    const members = familyInfo.members || []
    
    // 计算统计数据
    const totalMembers = members.length
    const activeMembers = members.filter(member => member.status === 'active').length
    const currentMonth = new Date().getMonth()
    const newMembers = members.filter(member => {
      const joinMonth = new Date(member.joinTime).getMonth()
      return joinMonth === currentMonth
    }).length

    this.setData({
      members,
      totalMembers,
      activeMembers,
      newMembers
    })
  },

  // 添加成员
  addMember() {
    this.setData({
      showModal: true,
      editingMember: null,
      memberForm: {
        nickname: '',
        role: 'member',
        phone: '',
        status: 'active',
        avatar: '',
        points: 100
      },
      roleIndex: 0
    })
  },

  // 编辑成员
  editMember(e) {
    const memberId = e.currentTarget.dataset.id
    console.log('编辑成员，ID:', memberId)
    
    // 优先使用 _id，如果没有则使用 id
    const member = this.data.members.find(m => (m._id === memberId) || (m.id === memberId))
    
    if (member) {
      console.log('找到要编辑的成员:', member)
      
      const roleIndex = member.role === 'member' ? 0 : 1
      // 确保表单字段名正确，包括积分同步
      const memberForm = {
        nickname: member.nickname || '',
        role: member.role || 'member',
        phone: member.phone || '',
        status: member.status || 'active',
        avatar: member.avatar || '',
        points: parseInt(member.points) || 0 // 确保积分是数字类型
      }
      
      this.setData({
        showModal: true,
        editingMember: member,
        memberForm,
        roleIndex
      })
      
      console.log('编辑成员表单初始化:', memberForm)
      console.log('原始成员数据:', member)
      console.log('当前表单数据:', this.data.memberForm)
    } else {
      console.error('未找到要编辑的成员:', memberId)
      wx.showToast({ title: '成员不存在', icon: 'error' })
    }
  },

  // 切换成员状态
  async toggleStatus(e) {
    const memberId = e.currentTarget.dataset.id
    const members = app.globalData.familyInfo.members
    const memberIndex = members.findIndex(m => (m._id || m.id) === memberId)
    
    if (memberIndex !== -1) {
      const newStatus = members[memberIndex].status === 'active' ? 'inactive' : 'active'
      
      try {
        // 同步更新云数据库
        const { userService } = require('../../../utils/cloud.js')
        const result = await userService.updateUserStatus(memberId, newStatus)
        
        if (result.success) {
          // 更新本地数据
          members[memberIndex].status = newStatus
          app.globalData.familyInfo.members = members
          this.loadMembers()
          
          const action = newStatus === 'active' ? '启用' : '禁用'
          wx.showToast({ title: `已${action}`, icon: 'success' })
          console.log(`成员状态更新成功: ${memberId} -> ${newStatus}`)
        } else {
          console.error('更新成员状态失败:', result.error)
          wx.showToast({ title: '状态更新失败', icon: 'error' })
        }
      } catch (error) {
        console.error('切换成员状态失败:', error)
        wx.showToast({ title: '状态更新失败', icon: 'error' })
      }
    }
  },

  // 删除成员
  deleteMember(e) {
    const memberId = e.currentTarget.dataset.id
    const member = this.data.members.find(m => (m._id || m.id) === memberId)
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除成员"${member.nickname}"吗？此操作不可恢复。`,
      success: async (res) => {
        if (res.confirm) {
          try {
            // 同步删除云数据库中的成员
            const { userService } = require('../../../utils/cloud.js')
            
            // 先从家庭中移除用户
            const removeResult = await userService.removeUserFromFamily(memberId)
            
            if (removeResult.success) {
              // 然后删除用户
            const result = await userService.deleteUser(memberId)
            
            if (result.success) {
              // 更新本地数据
                const members = app.globalData.familyInfo.members.filter(m => (m._id || m.id) !== memberId)
              app.globalData.familyInfo.members = members
              this.loadMembers()
              wx.showToast({ title: '删除成功', icon: 'success' })
              console.log(`成员删除成功: ${memberId}`)
            } else {
              console.error('删除成员失败:', result.error)
              wx.showToast({ title: '删除失败', icon: 'error' })
              }
            } else {
              console.error('从家庭中移除成员失败:', removeResult.error)
              wx.showToast({ title: '移除失败', icon: 'error' })
            }
          } catch (error) {
            console.error('删除成员失败:', error)
            wx.showToast({ title: '删除失败', icon: 'error' })
          }
        }
      }
    })
  },

  // 关闭弹窗
  closeModal() {
    this.setData({ showModal: false })
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 在微信小程序中，使用catchtap已经可以阻止事件冒泡
    return false
  },

  // 成员昵称输入
  onNicknameInput(e) {
    this.setData({
      'memberForm.nickname': e.detail.value
    })
  },

  // 显示角色选择器
  showRolePicker() {
    console.log('显示角色选择器')
    
    // 使用微信的actionSheet来模拟picker
    wx.showActionSheet({
      itemList: this.data.roles,
      success: (res) => {
        console.log('角色选择结果:', res)
        const index = res.tapIndex
        const role = index === 0 ? 'member' : 'chef'
        this.setData({
          roleIndex: index,
          'memberForm.role': role
        })
        
        wx.showToast({
          title: `已选择: ${this.data.roles[index]}`,
          icon: 'success',
          duration: 1500
        })
      },
      fail: (res) => {
        console.log('角色选择失败:', res)
        wx.showToast({
          title: '选择取消',
          icon: 'none',
          duration: 1000
        })
      }
    })
  },

  // 联系电话输入
  onPhoneInput(e) {
    this.setData({
      'memberForm.phone': e.detail.value
    })
  },

  // 状态切换
  onStatusChange(e) {
    const status = e.detail.value ? 'active' : 'inactive'
    this.setData({
      'memberForm.status': status
    })
  },

  // 选择头像
  chooseImage() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0]
        
        // 显示上传中提示
        wx.showLoading({
          title: '上传中...',
          mask: true
        })
        
        // 上传图片到云存储
        this.uploadImageToCloud(tempFilePath)
      }
    })
  },

  // 上传图片到云存储
  async uploadImageToCloud(tempFilePath) {
    try {
      // 生成唯一的文件名
      const timestamp = Date.now()
      const randomStr = Math.random().toString(36).substring(2, 8)
      const fileExtension = tempFilePath.split('.').pop()
      const cloudPath = `avatars/avatar_${timestamp}_${randomStr}.${fileExtension}`
      
      console.log('开始上传图片到云存储:', cloudPath)
      
      // 上传到云存储
      const uploadResult = await wx.cloud.uploadFile({
        cloudPath: cloudPath,
        filePath: tempFilePath
      })
      
      console.log('图片上传成功:', uploadResult)
      
      // 设置云存储URL
      this.setData({
        'memberForm.avatar': uploadResult.fileID
      })
      
      wx.hideLoading()
      wx.showToast({
        title: '头像上传成功',
        icon: 'success'
      })
      
    } catch (error) {
      console.error('图片上传失败:', error)
      wx.hideLoading()
      wx.showToast({
        title: '头像上传失败',
        icon: 'error'
      })
    }
  },

  // 保存成员
  async saveMember() {
    const { memberForm, editingMember } = this.data
    
    console.log('开始保存成员，表单数据:', memberForm)
    console.log('编辑的成员:', editingMember)
    
    // 验证表单
    if (!memberForm.nickname.trim()) {
      wx.showToast({ title: '请输入成员昵称', icon: 'none' })
      return
    }

    try {
      wx.showLoading({ title: '保存中...', mask: true })
      
      const { userService } = require('../../../utils/cloud.js')
      
      if (editingMember) {
        // 编辑现有成员
        console.log('编辑现有成员:', editingMember._id || editingMember.id)
        
        const updateData = {
          nickname: memberForm.nickname.trim(),
          phone: memberForm.phone.trim(),
          role: memberForm.role,
          status: memberForm.status,
          avatar: memberForm.avatar,
          points: parseInt(memberForm.points) || 0
        }
        
        console.log('要更新的数据:', updateData)
        
        // 更新用户信息
        const result = await userService.updateUser(editingMember._id || editingMember.id, updateData)
        
        if (result.success) {
          console.log('云数据库更新成功:', result)
          
          // 更新本地数据
          const members = app.globalData.familyInfo.members || []
          const memberIndex = members.findIndex(m => (m._id || m.id) === (editingMember._id || editingMember.id))
          
          if (memberIndex !== -1) {
            const updatedMember = {
              ...members[memberIndex],
              ...updateData
            }
            members[memberIndex] = updatedMember
            app.globalData.familyInfo.members = members
            
            console.log('本地数据更新成功，更新后的成员:', updatedMember)
          } else {
            console.warn('本地数据中未找到要更新的成员')
          }
          
          // 更新页面数据
          const pageMembers = [...this.data.members]
          const pageMemberIndex = pageMembers.findIndex(m => (m._id || m.id) === (editingMember._id || editingMember.id))
          
          if (pageMemberIndex !== -1) {
            pageMembers[pageMemberIndex] = {
              ...pageMembers[pageMemberIndex],
              ...updateData
            }
            this.setData({ members: pageMembers })
            console.log('页面数据更新成功')
          }
          
          wx.hideLoading()
          wx.showToast({ title: '编辑成功', icon: 'success' })
          console.log(`成员编辑成功: ${editingMember._id || editingMember.id}`)
          
          // 关闭弹窗并刷新数据
          this.closeModal()
          this.loadMembers()
        } else {
          wx.hideLoading()
          console.error('编辑成员失败:', result.error)
          wx.showToast({ title: '编辑失败', icon: 'error' })
          return
        }
      } else {
        // 添加新成员 - 这里需要先创建用户，然后添加到家庭
        console.log('添加新成员')
        
        const newMemberData = {
          nickname: memberForm.nickname.trim(),
          phone: memberForm.phone.trim(),
          role: memberForm.role,
          status: memberForm.status,
          avatar: memberForm.avatar,
          points: parseInt(memberForm.points) || 100, // 默认积分100
          joinTime: new Date().toISOString(),
          orderCount: 0,
          totalSpent: 0
        }
        
        console.log('新成员数据:', newMemberData)
        
        // 先创建用户
        const createResult = await userService.createUser(newMemberData)
        
        if (createResult.success) {
          const userId = createResult.data._id
          const familyId = 'xiaoweichufang'
          
          console.log('用户创建成功，ID:', userId)
          
          // 将用户添加到家庭
          const addToFamilyResult = await userService.addUserToFamily(userId, familyId, {
            familyId: familyId
          })
          
          if (addToFamilyResult.success) {
            console.log('用户添加到家庭成功')
            
            // 更新本地数据
            const members = app.globalData.familyInfo.members || []
            const newMember = {
              _id: userId,
              ...newMemberData
            }
            members.push(newMember)
            app.globalData.familyInfo.members = members
            
            wx.hideLoading()
            wx.showToast({ title: '添加成功', icon: 'success' })
            console.log(`新成员添加成功: ${userId}`)
            
            // 关闭弹窗并刷新数据
            this.closeModal()
            this.loadMembers()
          } else {
            wx.hideLoading()
            console.error('添加用户到家庭失败:', addToFamilyResult.error)
            wx.showToast({ title: '添加到家庭失败', icon: 'error' })
            return
          }
        } else {
          wx.hideLoading()
          console.error('创建用户失败:', createResult.error)
          wx.showToast({ title: '创建用户失败', icon: 'error' })
        }
      }
    } catch (error) {
      wx.hideLoading()
      console.error('保存成员失败:', error)
      wx.showToast({ title: '保存失败', icon: 'error' })
    }
  },

  // 页面下拉刷新
  onPullDownRefresh() {
    this.loadMembers()
    wx.stopPullDownRefresh()
  },

  // 积分管理相关函数
  // 打开积分管理弹窗
  managePoints(e) {
    const memberId = e.currentTarget.dataset.id
    const member = this.data.members.find(m => (m._id || m.id) === memberId)
    
    if (member) {
      this.setData({
        showPointsModal: true,
        selectedMember: member,
        pointsAdjustment: '',
        pointsSetValue: member.points || 0
      })
    }
  },

  // 关闭积分管理弹窗
  closePointsModal() {
    this.setData({
      showPointsModal: false,
      selectedMember: null,
      pointsAdjustment: '',
      pointsSetValue: ''
    })
  },

  // 快速调整积分
  quickAdjustPoints(e) {
    const amount = parseInt(e.currentTarget.dataset.amount)
    const currentPoints = this.data.selectedMember.points || 0
    const newPoints = Math.max(0, currentPoints + amount)
    
    this.setData({
      'selectedMember.points': newPoints,
      pointsSetValue: newPoints
    })
  },

  // 自定义积分调整输入
  onPointsAdjustmentInput(e) {
    this.setData({
      pointsAdjustment: e.detail.value
    })
  },

  // 应用自定义积分调整
  customAdjustPoints() {
    const adjustment = parseInt(this.data.pointsAdjustment)
    if (isNaN(adjustment)) {
      wx.showToast({
        title: '请输入有效数字',
        icon: 'none'
      })
      return
    }
    
    const currentPoints = this.data.selectedMember.points || 0
    const newPoints = Math.max(0, currentPoints + adjustment)
    
    this.setData({
      'selectedMember.points': newPoints,
      pointsSetValue: newPoints,
      pointsAdjustment: ''
    })
  },

  // 直接设置积分输入
  onPointsSetInput(e) {
    this.setData({
      pointsSetValue: e.detail.value
    })
  },

  // 直接设置积分
  setPoints() {
    const points = parseInt(this.data.pointsSetValue)
    if (isNaN(points) || points < 0) {
      wx.showToast({
        title: '请输入有效积分',
        icon: 'none'
      })
      return
    }
    
    this.setData({
      'selectedMember.points': points
    })
  },

  // 保存积分更改
  async savePointsChanges() {
    const { selectedMember } = this.data
    if (!selectedMember) return
    
    try {
      wx.showLoading({ title: '保存中...', mask: true })
      
      const { userService } = require('../../../utils/cloud.js')
      const result = await userService.updateUserPoints(selectedMember._id || selectedMember.id, selectedMember.points, 'set')
      
      if (result.success) {
        // 更新本地数据
        const members = app.globalData.familyInfo.members || []
        const memberIndex = members.findIndex(m => (m._id || m.id) === (selectedMember._id || selectedMember.id))
        if (memberIndex !== -1) {
          members[memberIndex].points = selectedMember.points
          app.globalData.familyInfo.members = members
        }
        
        wx.hideLoading()
        wx.showToast({ title: '积分更新成功', icon: 'success' })
        this.closePointsModal()
        this.loadMembers()
      } else {
        wx.hideLoading()
        console.error('更新积分失败:', result.error)
        wx.showToast({ title: '积分更新失败', icon: 'error' })
      }
    } catch (error) {
      wx.hideLoading()
      console.error('保存积分更改失败:', error)
      wx.showToast({ title: '保存失败', icon: 'error' })
    }
  },

  // 积分相关输入处理
  onPointsInput(e) {
    this.setData({
      'memberForm.points': parseInt(e.detail.value) || 0
    })
  },

  // 增加积分
  increasePoints(e) {
    const amount = parseInt(e.currentTarget.dataset.amount) || 1
    const currentPoints = this.data.memberForm.points || 0
    this.setData({
      'memberForm.points': currentPoints + amount
    })
  },

  // 减少积分
  decreasePoints(e) {
    const amount = parseInt(e.currentTarget.dataset.amount) || 1
    const currentPoints = this.data.memberForm.points || 0
    this.setData({
      'memberForm.points': Math.max(0, currentPoints - amount)
    })
  }
}) 